/*
 	Author: Mike Moore
 	Vectrics Flashrecruit
 	Open source job board and applicant tracking system built with enterprise Java.
 */
package org.vectrics.struts;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;

public class HttpRequestConverter {
	private static Logger log = Logger.getLogger(HttpRequestConverter.class);
	
	public static Map<String, Object> getSessionAttributes(HttpSession session) {
		Enumeration attributeNames = session.getAttributeNames();
		Map<String, Object> sessionAttributes = new HashMap<String, Object>();
		while (attributeNames.hasMoreElements()) {
			String name = (String)attributeNames.nextElement();
			Object value = session.getAttribute(name);
			sessionAttributes.put(name, value);
		}
		return(sessionAttributes);
	}
	
	public synchronized static Request convertRequest(HttpServletRequest httpRequest) {
		Request request = new Request();
		HttpSession session = httpRequest.getSession();
		
		request.setSession(httpRequest.getSession(true));
		
		request.setHttpRequest(httpRequest);
		request.setUserPrincipal(httpRequest.getUserPrincipal());
		request.setRemoteAddr(httpRequest.getRemoteAddr());
		request.setRemoteHost(httpRequest.getRemoteHost());
		
		Enumeration parameterNames = httpRequest.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = (String)parameterNames.nextElement();
			String parameterValue = httpRequest.getParameter(parameterName);
			request.addParameter(parameterName, parameterValue);
		}

		log.debug("Adding request attributes to request object");
		Enumeration attributeNames = httpRequest.getAttributeNames();
		while (attributeNames.hasMoreElements()) {
			String name = (String)attributeNames.nextElement();
			log.debug("Adding request attribute: " + name);
			Object value = httpRequest.getAttribute(name);
			request.attributes.put(name, value);
		}
		
		Map<String, Object> sessionAttributes = getSessionAttributes(httpRequest.getSession(true));
		request.setSessionAttributes(sessionAttributes);
		
		request.setLocale(httpRequest.getLocale());
		request.setContextPath(httpRequest.getContextPath());
		request.setRequestURL(httpRequest.getRequestURL());
		request.setRequestURI(httpRequest.getRequestURI());
		request.setQueryString(httpRequest.getQueryString());
		request.setSessionId(httpRequest.getSession().getId());
		return(request);
	}
}
